package com.sjy.ylxt.aspect;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class OperateLogAspect {
    //

    /** 换行符 */
    private static final String LINE_SEPARATOR = System.lineSeparator();

    @Pointcut("execution(* com.sjy.ylxt.controller..*(..))")
    public void webLog() {}

    /**
     * 在切点之前织入
     * @param joinPoint
     * @throws Throwable
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 打印请求相关参数
        log.info("");
        log.info("----------- 接口 Start -----------");
        // 打印请求 Method + url
        log.info("URL           : [{}] {}", request.getMethod(), request.getRequestURL().toString());
        // 打印请求入参
        log.info("Request       : {}", JSON.toJSONString(joinPoint.getArgs()));
    }

    @AfterReturning(value = "webLog()", returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) {
        log.info("Response      : {}", result);
        log.info("----------- 接口 End -----------");
    }

//    /**
//     * 环绕
//     * @param proceedingJoinPoint
//     * @return
//     * @throws Throwable
//     */
//    @Around("webLog()")
//    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
//        long startTime = System.currentTimeMillis();
//        Object result;
//        try {
//            result = proceedingJoinPoint.proceed();
//        } catch (IllegalArgumentException | IllegalStateException e) {
//            result = "[Can't Resolve] " + e.getMessage();
//        }
//
//        return result;
//    }


}
